package net.mof.manual.meta

import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import net.mof.manual.MarkedClassInfo
import net.mof.manual.Utils.deserializeClassName
import net.mof.manual.Utils.jsonObject
import net.mof.manual.Utils.serializeClassName
import net.mof.manual.Utils.stringClassName
import net.mof.manual.Utils.textUtilsClassName
import net.mof.manual.Utils.upFirstChar

/**
 *
 * 序列化的类型
 *
 * Created by LiYueHui on 2020/2/2.
 */
class SerializerFeildMetaInfo : BaseFieldMetaInfo() {
    var serializerTypeName: TypeName? = null
    var deserializerTypeName: TypeName? = null
    var typeName: TypeName? = null

    override fun optField(): String = "String"

    override fun instanceTypeName(): TypeName = stringClassName

    override fun jsonToTypeGet(builder: CodeBlock.Builder, markedClassInfo: MarkedClassInfo) {
        val t = ParameterizedTypeName.get(
                deserializeClassName, typeName)

        builder.beginControlFlow("if (!\$T.isEmpty(\$L))", textUtilsClassName,
                value)
        builder.addStatement("\$T \$L = new \$T()", t, value + "_de",
                deserializerTypeName)
        builder.addStatement("\$L.set\$L(\$L.deserializer(\$L))",
                markedClassInfo.getFileName()?.toLowerCase(),
                upFirstChar(filedName()), value + "_de", value).endControlFlow()
    }

    override fun typeToJsonObjectPut(builder: CodeBlock.Builder?, param: String?) {
        val t = ParameterizedTypeName.get(serializeClassName,
                typeName);
        builder?.addStatement("\$T \$L = new \$T()", t, value + "_de",
                serializerTypeName);

        builder?.addStatement("\$T \$L = \$L.serializer(\$L.get\$L())",
                stringClassName, value, value + "_de", param,
                upFirstChar(filedName()));
        builder?.beginControlFlow("if(!\$T.isEmpty(\$L))", textUtilsClassName,
                value);
        builder?.addStatement("\$L.put(\$S,\$L)", jsonObject, value, value);
        builder?.endControlFlow();
    }
}